package com.vnp.cooking;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.vnp.cooking.UIcontrols.swipedimiss.SwipeDismissListViewTouchListener;
import com.vnp.cooking.adapter.ListNguyenlieuAdapter;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.bean.ObjNguyenlieu;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.KeyboardHelper;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class TaoMonAnNguyenLieuActivity extends Activity implements OnClickListener{
	
	ImageButton btnBack; 
	TextView titleScreen;
	Button btnDone;
	Button btnUp, btnDown;
	TextView txtCountEater;
	int countEater;
	
	// list objnguyelieu
	public static ArrayList<ObjNguyenlieu> objNguyenlieus = new ArrayList<ObjNguyenlieu>();
	ObjCookpad objCookpad = new ObjCookpad();
	
	// khai bao adapter
	ListNguyenlieuAdapter adapter;
	ListView lsNguyenlieu;
	
	// khai bao 2 cai edittext nguyen lieu va so luong
	EditText edtNguyenlieu, edtSoluong;
	Button btnThem;
	View footerView;
	
	// swipe delete item
	PreferenceHelper preferenceHelper;
	
	JSONArray data;
	Dialog d, dArlert, dChuapost;
	boolean isProccess = false;
	Handler mHandler = new Handler();
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			updateNguyenlieu();
		}
	};
	
	Runnable rThoat = new Runnable() {
		
		@Override
		public void run() {
			closeActivity();
		}
	};
	
	ProgressDialog progressDialog;
	int sizeArray;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tao_mon_an_nguyen_lieu);
		preferenceHelper = new PreferenceHelper(this);

		sizeArray = objNguyenlieus.size();
		
		// log thu cam nghi ra
		
		titleScreen = (TextView) findViewById(R.id.txt_nguyenlieu_cookpad_title);
		
		btnBack = (ImageButton) findViewById(R.id.btn_back);
		btnDone = (Button) findViewById(R.id.btn_themnl_done);
		
		// tang giam nguoi dung
		btnUp = (Button) findViewById(R.id.btn_up);
		btnDown = (Button) findViewById(R.id.btn_down);
		
		// hien thi so nguoi dung
		txtCountEater = (TextView) findViewById(R.id.txt_count_eater);
		
		// khai bao listview va adapter
		lsNguyenlieu = (ListView) findViewById(R.id.ls_nguyenlieu);
		adapter = new ListNguyenlieuAdapter(TaoMonAnNguyenLieuActivity.this, objNguyenlieus);
		
		// addfooter
		addFooterListview();
		
		// set adapter cho listview
		lsNguyenlieu.setAdapter(adapter);
		
		// set click cho cac button
		btnBack.setOnClickListener(this);
		btnDone.setOnClickListener(this);
		btnUp.setOnClickListener(this);
		btnDown.setOnClickListener(this);
		btnThem.setOnClickListener(this);
		
		// set swipe nguyen lieu
		SwipeDismissListViewTouchListener touchListener =
	        new SwipeDismissListViewTouchListener(
	                lsNguyenlieu,
	                new SwipeDismissListViewTouchListener.OnDismissCallback() {
	                    @Override
	                    public void onDismiss(ListView listView, int[] reverseSortedPositions) {
	                        for (int position : reverseSortedPositions) {
	                            adapter.remove(adapter.getItem(position));
	                        }
	                        adapter.notifyDataSetChanged();
	                    }
	                });
		
		lsNguyenlieu.setOnTouchListener(touchListener);
		lsNguyenlieu.setOnScrollListener(touchListener.makeScrollListener());
		Log.i("DATA", "Kich thuoc: "+objNguyenlieus.size());
		
		setFont();
		
	}
	
	
	private void setFont() {
		titleScreen.setTypeface(Utils.getTypefaceRegular(TaoMonAnNguyenLieuActivity.this));
		btnDone.setTypeface(Utils.getTypefaceRegular(TaoMonAnNguyenLieuActivity.this));
	}

	@Override
	protected void onResume() {
		super.onResume();
	}



	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_back:
			if (isProccess == true) {
				showDialogProcess();
			} else {
				if (objNguyenlieus.isEmpty()) {
					closeActivity();
				} else {
					if (sizeArray != objNguyenlieus.size()) {
						showDialogCanhbaochuapost();
					} else {
						closeActivity();
					}
					
				}
			}
			
			
			break;
			
		case R.id.btn_themnl_done:
			if (objNguyenlieus.isEmpty()) {
				Toast.makeText(TaoMonAnNguyenLieuActivity.this, "Nguyên liệu không được để trống.", Toast.LENGTH_SHORT).show();
			} else {
				KeyboardHelper.hideSoftKeyboard(TaoMonAnNguyenLieuActivity.this);
				progressDialog = ProgressDialog.show(this, "", "Đang cập nhật đặc điểm công thức...");
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						if (null != progressDialog && progressDialog.isShowing())
							progressDialog.dismiss();
					}
				}, 90000);
				isProccess = true;
				saveNguyenlieu();
			}
			
			break;

		
		case R.id.btn_up:
			countEater = countEater + 1;
			txtCountEater.setText(""+countEater);
			break;
		case R.id.btn_down:
			countEater = countEater - 1;
			txtCountEater.setText(""+countEater);
			if (countEater < 1) {
				countEater = 1;
				txtCountEater.setText("1");
			}
			break;
		case R.id.btn_them_nguyenlieu:
			addNguyenlieu();
			break;
		case R.id.btn_dong:
			d.dismiss();
			mHandler.postDelayed(rThoat, 200);
			break;
		}
 	}
	
	
	// add nguyen lieu vao list 
	public void addNguyenlieu() {
		if (edtNguyenlieu.getText().toString().matches("")) {
			Toast.makeText(TaoMonAnNguyenLieuActivity.this, "Nguyên liệu không được để trống.", Toast.LENGTH_SHORT).show();
		} else {
			ObjNguyenlieu objNguyenlieu = new ObjNguyenlieu(edtNguyenlieu.getText().toString(), edtSoluong.getText().toString());
			objNguyenlieus.add(objNguyenlieu);
			edtNguyenlieu.setText("");
			edtSoluong.setText("");
			edtNguyenlieu.requestFocus();
			adapter.notifyDataSetChanged();
		}
	}
	
	// add footer to listview
	public void addFooterListview() {
		View footerView = getLayoutInflater().inflate(R.layout.footer_listview_nguyenlieu, lsNguyenlieu, false);
		lsNguyenlieu.addFooterView(footerView);
		edtNguyenlieu = (EditText) footerView.findViewById(R.id.edt_ten_nguyen_lieu);
		edtSoluong = (EditText) footerView.findViewById(R.id.edt_soluong);
		btnThem = (Button) footerView.findViewById(R.id.btn_them_nguyenlieu);
		edtSoluong.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if(actionId == EditorInfo.IME_ACTION_DONE){
					addNguyenlieu();
					return true;
				}
				return false;
			}
		});
		
		edtNguyenlieu.setTypeface(Utils.getTypefaceRegular(TaoMonAnNguyenLieuActivity.this));
		edtSoluong.setTypeface(Utils.getTypefaceRegular(TaoMonAnNguyenLieuActivity.this));
		btnThem.setTypeface(Utils.getTypefaceRegular(TaoMonAnNguyenLieuActivity.this));
	}
	
	public void checkNguyenlieuNextStep() {
		
		// set gia tri nguoi an cho object Cookpad
		objCookpad.setIngredientsForPerson(countEater);
		// set gia tri nguyen lieu
		objCookpad.setObjNguyenlieus(objNguyenlieus);
		
		KeyboardHelper.hideSoftKeyboard(TaoMonAnNguyenLieuActivity.this);
		Intent t = new Intent(TaoMonAnNguyenLieuActivity.this, TaoMonAnCachLamActivity.class);
		t.putExtra("objCookpad", objCookpad);
		startActivity(t);
	}
	
	// save nguyen lieu lai
	public void saveNguyenlieu() {
		data = new JSONArray();
		for (int i = 0; i < objNguyenlieus.size(); i++) {
			data.put(objNguyenlieus.get(i).getJSONObject());
		}
//		updateNguyenlieu();
//		finish();
		mHandler.removeCallbacks(r);
		mHandler.postDelayed(r, 200);
	}
	
	// upnguyen llieu
	void updateNguyenlieu(){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				isProccess = false;
				progressDialog.dismiss();
				Toast.makeText(TaoMonAnNguyenLieuActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					isProccess = false;
					progressDialog.dismiss();
					switch (status) {
					case 200:
//						showDialogCapnhatNguyenlieuthanhcong();
						mHandler.postDelayed(rThoat, 200);
						Log.i("DATA", "Capnhat nguyen lieu thanh cong");
						break;
					case 400:
						Toast.makeText(TaoMonAnNguyenLieuActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						Log.i("DATA", "Capnhat nguyen lieu that bai : thieu du lieu");
						break;
					case 404:
						Toast.makeText(TaoMonAnNguyenLieuActivity.this, "Cập nhật thất bại.", Toast.LENGTH_SHORT).show();
						Log.i("DATA", "Capnhat nguyen lieu that bai: id khong trung");
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
			}
		});
		httpClientHelper.uploadNguyenlieu(preferenceHelper.getID(), preferenceHelper.getRecipeId(), data);
	}
	
	void closeActivity(){
		finish();
		overridePendingTransition(R.anim.open_main, R.anim.close_next);
	}


	@Override
	public void onBackPressed() {
		closeActivity();
	}
	
	void showDialogCapnhatNguyenlieuthanhcong() {
		d = new Dialog(this, R.style.DialogSlideAnimLeft);
		d.requestWindowFeature(Window.FEATURE_NO_TITLE);
		d.setContentView(R.layout.dialog_chua_hotro);
		TextView txtThongbao = (TextView) d.findViewById(R.id.str_canhbao_thoat);
		
		Button btnDong = (Button) d.findViewById(R.id.btn_dong);
		
		txtThongbao.setText("Bạn đã cập nhật nguyên liệu thành công.");
		d.show();
		d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		d.setCanceledOnTouchOutside(true);
		d.getWindow().setGravity(Gravity.CENTER);
		d.show();
		
		// setonclick
		btnDong.setOnClickListener(this);
	}
	
	// show dialog dang thuc hien 1 hanh dong noa do
		public void showDialogProcess() {
			dArlert = new Dialog(TaoMonAnNguyenLieuActivity.this, R.style.DialogSlideAnimLeft);
			dArlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dArlert.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dArlert.findViewById(R.id.str_canhbao_thoat);
			Button btnThoat = (Button) dArlert.findViewById(R.id.btn_thoat);
			Button btnKoThoat = (Button) dArlert.findViewById(R.id.btn_ko_thoat);
			
			
			btnThoat.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dArlert.dismiss();
					mHandler.removeCallbacks(r);
					closeActivity();
				}
			});
			
			btnKoThoat.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dArlert.dismiss();
				}
			});

			dArlert.setCanceledOnTouchOutside(true);
			dArlert.show();
			dArlert.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dArlert.getWindow().setGravity(Gravity.CENTER);
		}
		
		void showDialogCanhbaochuapost() {
			dChuapost = new Dialog(TaoMonAnNguyenLieuActivity.this, R.style.DialogSlideAnimLeft);
			dChuapost.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dChuapost.setContentView(R.layout.dialog_thoat_process);

			// khai bao cac thanh phan
			TextView txtArlert = (TextView) dChuapost.findViewById(R.id.str_canhbao_thoat);
			Button btnCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_thoat);
			Button btnKoCapnhatThoat = (Button) dChuapost.findViewById(R.id.btn_ko_thoat);
			
			txtArlert.setText("Bạn chưa cập nhật nguyên liệu. Bạn có muốn cập nhật và thoát?");
			btnCapnhatThoat.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
					progressDialog = ProgressDialog.show(TaoMonAnNguyenLieuActivity.this, "", "Đang cập nhật đặc điểm công thức...");
					mHandler.postDelayed(new Runnable() {

						@Override
						public void run() {
							if (null != progressDialog && progressDialog.isShowing())
								progressDialog.dismiss();
						}
					}, 90000);
					isProccess = true;
					saveNguyenlieu();
				}
			});
			
			btnKoCapnhatThoat.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dChuapost.dismiss();
					objNguyenlieus.clear();
					mHandler.postDelayed(rThoat, 300);
				}
			});

			dChuapost.setCanceledOnTouchOutside(true);
			dChuapost.show();
			dChuapost.getWindow().setBackgroundDrawable(new ColorDrawable(0));
			dChuapost.getWindow().setGravity(Gravity.CENTER);
		}
	
 }
